package com.iu.filter;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.iu.util.SHA1;
import com.iu.util.WeixinInfoUtil;

public class WeixinUrlFilter implements Filter{

	private Logger log = Logger.getLogger( WeixinUrlFilter.class );
	
	@Override
	public void destroy() {
		log.info("destroy");
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain )
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		
		if( isGet ){
			String signature = request.getParameter("signature");// 微信加密签名
			String timestamp = request.getParameter("timestamp");// 时间戳
			String nonce = request.getParameter("nonce");// 随机数
			String echostr = request.getParameter("echostr");// 随机字符串
			Writer out = response.getWriter();
			log.debug("收到验证请求：");
			log.debug("　　signature="+signature);
			log.debug("　　timestamp="+timestamp);
			log.debug("　　nonce="+nonce);
			log.debug("　　echostr="+echostr);
			if( StringUtils.isBlank(echostr) ){
				//这几个参数为空时，排序会报错。
				chain.doFilter( req, res );
			}else{
				// 重写totring方法，得到三个参数的拼接字符串
				List<String> list = new ArrayList<String>(3) {
					private static final long serialVersionUID = 2621444383666420433L;
					public String toString() {
						return this.get(0) + this.get(1) + this.get(2);
					}
				};
				list.add(WeixinInfoUtil.TOKEN);
				list.add(timestamp);
				list.add(nonce);
				Collections.sort(list);// 排序
				String tmpStr = SHA1.encode(list.toString());// SHA-1加密
				if (signature.equals(tmpStr)) {
					out.write(echostr);// 请求验证成功，返回随机码
				} else {
					out.write("check error!");
				}
			}
			out.flush();
			out.close();
		}else{
			chain.doFilter( req, res );
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		log.info("init");
	}
	

}
